package io.github.xxyopen.novel.getpic;


import io.github.xxyopen.novel.core.common.exception.BusinessException;
import io.github.xxyopen.novel.dao.entity.BookInfo;
import io.github.xxyopen.novel.service.BookService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@SpringBootTest
public class getPicture {

    @Autowired
    BookService bookService;

    @Test
    public void getPic() {

        List<BookInfo> allBookInfo = bookService.getAllBookInfo();

        allBookInfo.forEach(bookInfo -> {
            String bookName = bookInfo.getBookName();
            String searchText = bookName + "的小说封面";
            //去除所有的空格

            try {
                searchText = URLEncoder.encode(searchText, StandardCharsets.UTF_8);
                String fetchUrl = String.format("https://cn.bing.com/images/search?q=%s&mmasync=1", searchText);
                Document doc = Jsoup.connect(fetchUrl).get();
                Element first = doc.select("img.mimg").getFirst();
                String imgSrc = first.attr("src");
                System.out.println("小说说封面--" + imgSrc);
                bookInfo.setPicUrl(imgSrc);
                bookService.updateBookPicUrl(bookInfo);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

}
